from fastapi import APIRouter
from models import db, Book,BookCreate,BookQuery

book_router = APIRouter()

# 录入图书信息
@book_router.post('/createBook', summary='创建图书',tags=["图书相关接口"])
async def creatBook(book: BookCreate):
    # 创建返回值信息的初始值
    success = True  # 是否成功创建
    msg = "创建成功"  # 返回信息
    # 补全属性
    # TODO 这种补全模型的方法很危险，绕开了pydantic的类型检查，亟待优化
    bookModel = book.dict(by_alias=True)
    print(type(bookModel))
    bookModel["available_status"] = True
    # 如果验证通过则创建
    if success:
        ret = db.books.insert_one(bookModel)
        print(ret)
    return {'success': success, 'msg': msg}

# 删除图书信息
@book_router.get('/deleteBook', summary='删除图书信息',tags=["图书相关接口"])
async def deleteBook(book_id: str):
    success= True
    msg = "删除成功"
    book=db.books.find_one({"book_id":book_id})
    if book:
        book=Book(**book)
        if book.available_status:
            db.books.delete_one({"book_id":book_id})
        else:
            msg="书本不在库"
            success=False
    else:
        msg="查无此书"
        success=False
    return {'success': success,"msg":msg}

# 查询图书信息
@book_router.post('/queryBook', summary='查询图书信息',tags=["图书相关接口"])
async def queryBook(book: BookQuery):
    page = book.page
    size = book.size
    skip = size * (page - 1)
    # 返回数据总条数
    dataCount = db.books.find({
        "book_id": {"$regex": book.book_id},
        "book_name": {"$regex": book.book_name},
        "book_author": {"$regex": book.book_author},
        "publisher": {"$regex": book.publisher},
        "pub_date": {"$regex": book.pub_date},
        "isbn": {"$regex": book.isbn}}).count()
    res = db.books.find({
        "book_id": {"$regex": book.book_id},
        "book_name": {"$regex": book.book_name},
        "book_author": {"$regex": book.book_author},
        "publisher": {"$regex": book.publisher},
        "pub_date": {"$regex": book.pub_date},
        "isbn": {"$regex": book.isbn}}).limit(size).skip(skip)
    books = []
    for it in res:
        # print(it)
        # print(type(it))
        bookData = Book(**it)
        books.append(bookData)
    return {'data': books, 'data_count': dataCount}


@book_router.get('/getBookDetail',summary='精确查询',tags=["图书相关接口"])
async def getBookDetail(book_id :str):
    res = db.books.find_one({"book_id": book_id})
    if res:
        res = Book(**res)
        if hasattr(res,'id'):
            delattr(res,'id')

    return {'book':res}